<?php

// 判断是否是在微信浏览器里
function isWeixinBrowser($from = 0)
{
    if ((!$from && defined('IN_WEIXIN') && IN_WEIXIN) || isset ($_GET ['is_stree']))
        return true;

    $agent = $_SERVER ['HTTP_USER_AGENT'];
    if (!strpos($agent, "icroMessenger")) {
        return false;
    }
    return true;
}

// php获取当前访问的完整url地址
function GetCurUrl()
{
    $url = HTTP_PREFIX;
    if ($_SERVER ['SERVER_PORT'] != '80' && $_SERVER ['SERVER_PORT'] != '443') {
        $url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI'];
    } else {
        $url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
    }
    // 兼容后面的参数组装
    if (stripos($url, '?') === false) {
        $url .= '?t=' . time();
    }
    return $url;
}

// 获取当前用户的OpenId
function get_openid($openid = NULL)
{
    $token = get_token();
    if ($openid !== NULL && $openid != '-1' && $openid != '-2') {
        session('openid_' . $token, $openid);
    } elseif (!empty ($_REQUEST ['openid']) && $_REQUEST ['openid'] != '-1' && $_REQUEST ['openid'] != '-2') {
        session('openid_' . $token, $_REQUEST ['openid']);
    }
    $openid = session('openid_' . $token);

    $isWeixinBrowser = isWeixinBrowser();
    if ((empty ($openid) || $openid == '-1') && $isWeixinBrowser && $_REQUEST ['openid'] != '-2' && IS_GET && !IS_AJAX) {
        $callback = GetCurUrl();
        $openid = OAuthWeixin($callback, $token, true);
        if ($openid != false && $openid != '-2') {
            session('openid_' . $token, $openid);
        }
    }
    if (empty ($openid)) {
        return '-1';
    }
    return $openid;
}

// 获取当前用户的Token
function get_token($token = NULL)
{

    session('token','gh_a9b4dbd32e0d');
    $stoken ='gh_a9b4dbd32e0d';
    return $stoken;
    $reset = false;
    if ($token !== NULL && $token != '-1') {
        session('token', $token);
        $reset = true;
    } elseif (!empty ($_REQUEST ['token']) && $_REQUEST ['token'] != '-1') {
        session('token', $_REQUEST ['token']);
        $reset = true;
    }
    $token = session('token');
    if (!empty ($token) && $token != '-1' && $stoken != $token && $GLOBALS ['is_wap']) {
        session('mid', null);
    }
    if (empty ($token)) {
        $token = -1;
    }

    return $token;
}

// 获取公众号的信息
function get_token_appinfo($token = '', $field = '')
{

    //获取微信配置
    $wechat_list = M('wx_user')->select();
    return $wechat_list[0];
}

function get_access_token_by_apppid($appid, $secret, $update = false)
{
    if (empty ($appid) || empty ($secret)) {
        return 0;
    }

    $key = 'access_token_apppid_' . $appid . '_' . $secret;
    $res = S($key);
    if ($res !== false && !$update)
        return $res;

    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&secret=' . $secret . '&appid=' . $appid;
    $tempArr = json_decode(get_data($url), true);
    if (@array_key_exists('access_token', $tempArr)) {
        S($key, $tempArr ['access_token'], $tempArr ['expires_in']);
        return $tempArr ['access_token'];
    } else {
        return 0;
    }
}

function OAuthWeixin($callback, $token = '', $is_return = false)
{
    if ((defined('IN_WEIXIN') && IN_WEIXIN) || isset ($_GET ['is_stree']) )
        return false;

    $isWeixinBrowser = isWeixinBrowser();
    if (!$isWeixinBrowser) {
        return false;
    }
    $callback = urldecode($callback);
    if (strpos($callback, '?') === false) {
        $callback .= '?';
    } else {
        $callback .= '&';
    }
    if (!empty ($token) && strpos($token, ':') !== false) {
        $arr = explode(':', $token);
        $info ['appid'] = $arr [0];
        $info ['secret'] = $arr [1];
    } else {
        $info = get_token_appinfo($token);
    }

    if (empty ($info ['appid'])) {
        redirect($callback . 'openid=-2');
    }
    $param ['appid'] = $info ['appid'];
    if ($_GET ['state'] != 'weiphp') {
        $param ['redirect_uri'] = $callback;
        $param ['response_type'] = 'code';
        $param ['scope'] = 'snsapi_userinfo';
        $param ['state'] = 'weiphp';
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query($param) . '#wechat_redirect';
        redirect($url);
    } elseif ($_GET ['state'] == 'weiphp') {
        if (empty ($_GET ['code'])) {
            exit ('code获取失败');
        }

        $param ['code'] = I('code');
        $param ['grant_type'] = 'authorization_code';

        if ($info ['is_bind']) {
            $param ['appid'] = I('appid');
//            $param ['component_appid'] = C('COMPONENT_APPID');
//            $param ['component_access_token'] = D('Addons://PublicBind/PublicBind')->_get_component_access_token();

            $url = 'https://api.weixin.qq.com/sns/oauth2/component/access_token?' . http_build_query($param);
        } else {
            $param ['secret'] = $info ['appsecret'];

            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query($param);
        }

        $content = get_data($url);
        $content = json_decode($content, true);
        if ($is_return) {
            session('openinfo',$content);
            return $content ['openid'];
        } else {
            redirect($callback . 'openid=' . $content ['openid']);
        }
    }
}



function get_data($url, $timeout = 5){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return $file_contents;
}
